package edu.sdjzu.exam.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handle -> {
            SaRouter
                    .match("/api/auth/**").free(r -> {})  // 登录注册等接口放行
                    .match("/api/rbac/**", () -> StpUtil.checkRoleOr("teacher", "super_admin"))  // teacher 和 super_admin 角色可访问
                    .match("/api/exams/my", () -> StpUtil.checkRoleOr("teacher", "student"))  // 获取我的考试列表，教师或学生可访问
                    .match("/api/exams/*", () -> StpUtil.checkRoleOr("teacher", "student"))  // 获取单个考试信息，教师或学生可访问
                    .match("/api/exams/**", () -> StpUtil.checkRole("teacher"))  // 其他考试相关接口，仅教师可访问
                    .match("/api/questions/**", () -> StpUtil.checkRole("teacher"))  // 仅教师可访问
                    .match("/api/exam-assignments/**", () -> StpUtil.checkRoleOr("teacher", "student"))  // 教师或学生可访问
                    .match("/api/user-groups/**", () -> StpUtil.checkRole("teacher"))  // 仅教师可访问
                    .match("/api/group-grades/**", () -> StpUtil.checkPermission("view_analytics"))  // 需要 view_analytics 权限
                    .match("/**", () -> StpUtil.checkLogin());  // 其他接口需要登录
        })).addPathPatterns("/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}